//
//  LuckyTurntableView.swift
//  LuckyTurntable
//
//  Created by Yinyin Zeng on 31/5/20.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit
//幸运转盘
class LuckyTurntableView: UIView {
    
    private let turntableView = UIView() //转盘底盘
    private let luckyWheel = UIView()//转盘
    private let startBtn = UIButton()//开始按钮
    var displayLink  = CADisplayLink()
    
    //定义闭包
    var rotateFinishBlock: (()->())?
    
    private var wheelBtnArr:[UIButton] = []
    private var currenBtn = UIButton()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
        
        //每秒钟执行大约60次
        displayLink = CADisplayLink.init(target: self, selector: #selector(startRotate))
        displayLink.add(to: RunLoop.main, forMode: .default)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        self.layer.contents = UIImage(named: "LuckyBackground")?.cgImage
        
        //转盘底盘
        turntableView.layer.contents = UIImage(named: "LuckyBaseBackground")?.cgImage
        turntableView.frame = CGRect(x: 0, y: 0, width: 286, height: 286)
        turntableView.center = self.center
        self.addSubview(turntableView)
        
        //转盘
        luckyWheel.layer.contents = UIImage(named: "LuckyRotateWheel")?.cgImage
        luckyWheel.frame = CGRect(x: 0, y: 0, width: 286, height: 286)
        luckyWheel.center = self.center
        self.addSubview(luckyWheel)
        
        
        
        //开始按钮
        startBtn.setBackgroundImage(UIImage(named: "LuckyCenterButton"), for: .normal)
        startBtn.setBackgroundImage(UIImage(named: "LuckyCenterButtonPressed"), for: .highlighted)
        startBtn.frame = CGRect(x: 0, y: 0, width: 81, height: 81)
        startBtn.center = self.center
        startBtn.addTarget(self, action: #selector(startBtnAction), for: .touchUpInside)
        self.addSubview(startBtn)
        
        //转盘内的按钮
        for i in 0..<12 {
            let wheelBtn = UIButton()
            wheelBtn.tag = i //方便用于旋转
            wheelBtn.frame =  CGRect(x: 0, y: 0, width: 68, height: 143)
            wheelBtn.center = CGPoint(x: luckyWheel.bounds.width / 2,y: luckyWheel.bounds.width / 2)
            //锚点
            wheelBtn.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
            //设置图片
            let wheelImage = self.clipImage(image:  UIImage(named: "LuckyAstrology")!, index: i)
            wheelBtn.setImage(wheelImage, for: .normal)
            //图片位置
            wheelBtn.imageEdgeInsets = UIEdgeInsets(top: -50, left: 0, bottom: 0, right: 0)
            
            //设置选中图片
            let wheelImagePressed = self.clipImage(image:  UIImage(named: "LuckyAstrologyPressed")!, index: i)
            wheelBtn.setImage(wheelImagePressed, for: .selected)
            
            
            //设置选中背景图
            wheelBtn.setBackgroundImage(UIImage(named: "LuckyRototeSelected"), for: .selected)
            
            //监听按钮点击
            wheelBtn.addTarget(self, action: #selector(wheelBtnAction), for: .touchUpInside)
            
            //按钮的旋转角度
            let rotationAngle = CGFloat(2 * Double.pi / 12) * CGFloat(i)
            wheelBtn.transform = CGAffineTransform(rotationAngle: rotationAngle)
            luckyWheel.addSubview(wheelBtn)
        }
    }
    
    //开始旋转的方法
    @objc func startBtnAction(sender:UIButton){
        
        if self.luckyWheel.layer.animation(forKey: "animaKey") != nil{
            return
        }
        
        if !self.currenBtn.isSelected{
            return
        }
        
        //暂停自旋转
        displayLink.isPaused = true
        
        //禁止用户点击
        self.luckyWheel.isUserInteractionEnabled = false
        
        //使用核心动画
        let anima = CABasicAnimation.init(keyPath: "transform.rotation.z")
        //旋转到最上面的夹角
        let angle = CGFloat(2 * Double.pi / 12) * CGFloat(self.currenBtn.tag)
        anima.toValue = CGFloat(2 * Double.pi * 5) - angle
        anima.duration = 3
        //不回到原来的位置
        anima.fillMode = .forwards
        anima.isRemovedOnCompletion = false
        self.luckyWheel.layer.add(anima, forKey: "animaKey") //用于移除
        //核心动画转动的layer，view实际上没有变动，需要手动调整
        self.luckyWheel.transform = CGAffineTransform(rotationAngle: -angle)
        
        let popTime = DispatchTime.now() + anima.duration //延迟执行
        DispatchQueue.main.asyncAfter(deadline: popTime) {
            //允许用户点击
            self.luckyWheel.isUserInteractionEnabled = true
            
            if let block = self.rotateFinishBlock {
               block()
            }
            
            //移除核心动画
            self.luckyWheel.layer.removeAnimation(forKey: "animaKey")
            
        }
        
        
        
    }
    
    //自旋转方法
    @objc func startRotate(){
        
        //每秒钟执行大约60次
        self.luckyWheel.transform = CGAffineTransform(rotationAngle: CGFloat(2 * Double.pi / 60 / 10)).concatenating(self.luckyWheel.transform)
        
    }
    
 
    
    @objc func wheelBtnAction(sender:UIButton){
        //清除上次选中状态
        currenBtn.isSelected = false
        
        sender.isSelected = true
        //记录当前选中按钮
        currenBtn = sender
    }

    //根据大图 切割出一部分图片
    func clipImage(image:UIImage,index:Int) -> UIImage{
        //计算rect 2为缩放因子
        let w = image.size.width / 12 * 2//UIScreen.main.scale
        let h = image.size.height * 2//UIScreen.main.scale
        let x = CGFloat(index) * w
        let y =  CGFloat(0)
        let cgImage = image.cgImage
        if let imageRef = cgImage!.cropping(to:CGRect(x: x, y: y, width: w, height: h)){
            return UIImage.init(cgImage: imageRef, scale: 2.3, orientation: .up)
        }
        return UIImage()
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    func currentViewController() -> (UIViewController?) {
       var window = UIApplication.shared.keyWindow
       if window?.windowLevel != UIWindow.Level.normal{
         let windows = UIApplication.shared.windows
         for  windowTemp in windows{
           if windowTemp.windowLevel == UIWindow.Level.normal{
              window = windowTemp
              break
            }
          }
        }
       let vc = window?.rootViewController
       return vc
    }

}
